<template>
  <div class="addreport">
    <div class="back">
      <el-button
        size="small"
        type="primary"
        plain
        icon="el-icon-arrow-left"
        @click="goback"
        >返 回</el-button
      >
      <el-button type="primary" size="small" @click="exportlist">
        <i class="el-icon-upload2" >导 出</i></el-button
      >
    </div>
    <div class="form">
      <el-form ref="formrefs" :model="formdata" label-width="15px" :rules="rules">
       <el-descriptions class="margin-top" :column="3" border>
        <el-descriptions-item label="报表企业" label-class-name="my-label-title" >
          <el-form-item label=" " prop="orgNo">
            <FilterSelect2
            v-model="formdata.orgNo"
            :optionlist="qiyelist"
            :valuekey="{ name: 'bizOrgName', value: 'bizOrgNo' }"
            :disabled="!isonlylook"
          ></FilterSelect2>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item label="报表名称" label-class-name="my-label-title">
          <el-form-item label=" " prop="reportName">
            <el-input
            size="small"
            v-model="formdata.reportName"
            placeholder="手动输入或者自动生成"
            :disabled="!isonlylook"
          ></el-input>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item label="填报时间" label-class-name="my-label-title">
          <el-form-item label=" " prop="createDate">
            <el-date-picker v-model="formdata.createDate" :disabled="!isonlylook" size="small" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" style="width:100%" placeholder="选择日期">
          </el-date-picker>
          </el-form-item>
        </el-descriptions-item>
      </el-descriptions>
      <div class="descriptions">
          <el-descriptions :column="3" border direction="vertical" class="deitem-falst">
            <el-descriptions-item label="油品名称" label-class-name="my-label">
              <el-form-item label=" " prop="oilName">
                <el-input size="small" v-model="formdata.oilName" placeholder="请输入" :disabled="!isonlylook"></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="输油能耗(度/吨)" label-class-name="my-label">
                <el-input size="small" v-model="formdata.oilEnergyConsumption" placeholder="自动计算" disabled></el-input>
            </el-descriptions-item>
            <el-descriptions-item label="输油总量(吨)" label-class-name="my-label">
              <el-form-item label=" " prop="oilTotal">
                <el-input size="small" v-model="formdata.oilTotal" placeholder="请输入" :disabled="!isonlylook"></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="输油温度(℃)" label-class-name="my-label">
              <el-input size="small" v-model="formdata.temperature" placeholder="请输入" :disabled="!isonlylook"></el-input>
            </el-descriptions-item>
            <el-descriptions-item label="油品密度" label-class-name="my-label">
              <el-input size="small" v-model="formdata.density" placeholder="请输入" :disabled="!isonlylook"></el-input>
            </el-descriptions-item>
            <el-descriptions-item label="油品粘度(cst)" label-class-name="my-label">
              <el-input size="small" v-model="formdata.oilViscosity" placeholder="请输入" :disabled="!isonlylook"></el-input>
            </el-descriptions-item>
          </el-descriptions>
          <el-descriptions :column="4" border direction="vertical" class="deitem">
            <el-descriptions-item label="尖电占比(%)" label-class-name="my-label">
              <el-input size="small" v-model="formdata.sharpUsageRate" placeholder="自动计算" disabled></el-input>
            </el-descriptions-item>
            <el-descriptions-item label="峰电占比(%)" label-class-name="my-label">
              <el-input size="small" v-model="formdata.peakUsageRate" placeholder="自动计算" disabled></el-input>
            </el-descriptions-item>
            <el-descriptions-item label="平电占比(%)" label-class-name="my-label">
              <el-input size="small" v-model="formdata.flatUsageRate" placeholder="自动计算" disabled></el-input>
            </el-descriptions-item>
            <el-descriptions-item label="谷电占比(%)" label-class-name="my-label">
              <el-input size="small" v-model="formdata.valleyUsageRate" placeholder="自动计算" disabled></el-input>
            </el-descriptions-item>
            <el-descriptions-item label="尖总电量(kWh)" label-class-name="my-label">
              <el-input size="small" v-model="formdata.sharpUsage" placeholder="自动计算" disabled></el-input>
            </el-descriptions-item>
            <el-descriptions-item label="峰总电量(kWh)" label-class-name="my-label">
              <el-input size="small" v-model="formdata.peakUsage" placeholder="自动计算" disabled></el-input>
            </el-descriptions-item>
            <el-descriptions-item label="平总电量(kWh)" label-class-name="my-label">
              <el-input size="small" v-model="formdata.flatUsage" placeholder="自动计算" disabled></el-input>
            </el-descriptions-item>
            <el-descriptions-item label="谷总电量(kWh)" label-class-name="my-label">
              <el-input size="small" v-model="formdata.valleyUsage" placeholder="自动计算" disabled></el-input>
            </el-descriptions-item>
          </el-descriptions>
          <el-descriptions :column="1" border direction="vertical" class="deitem-little">
            <el-descriptions-item label="总用电量(kWh)" label-class-name="my-label">
              <el-input size="small" v-model="formdata.totalElectricity" placeholder="自动计算" disabled></el-input>
            </el-descriptions-item>
          </el-descriptions>
          <el-descriptions :column="4" border direction="vertical" class="deitem">
            <el-descriptions-item label="尖电费占比(%)" label-class-name="my-label">
              <el-input size="small" v-model="formdata.sharpPriceRate" placeholder="自动计算" disabled></el-input>
            </el-descriptions-item>
            <el-descriptions-item label="峰电费占比(%)" label-class-name="my-label">
              <el-input size="small" v-model="formdata.peakPriceRate" placeholder="自动计算" disabled></el-input>
            </el-descriptions-item>
            <el-descriptions-item label="平电费占比(%)" label-class-name="my-label">
              <el-input size="small" v-model="formdata.flatPriceRate" placeholder="自动计算" disabled></el-input>
            </el-descriptions-item>
            <el-descriptions-item label="谷电费占比(%)" label-class-name="my-label">
              <el-input size="small" v-model="formdata.valleyPriceRate" placeholder="自动计算" disabled></el-input>
            </el-descriptions-item>
            <el-descriptions-item label="尖总电费(元)" label-class-name="my-label">
              <el-input size="small" v-model="formdata.sharpPrice" placeholder="自动计算" disabled></el-input>
            </el-descriptions-item>
            <el-descriptions-item label="峰总电费(元)" label-class-name="my-label">
              <el-input size="small" v-model="formdata.peakPrice" placeholder="自动计算" disabled></el-input>
            </el-descriptions-item>
            <el-descriptions-item label="平总电费(元)" label-class-name="my-label">
              <el-input size="small" v-model="formdata.flatPrice" placeholder="自动计算" disabled></el-input>
            </el-descriptions-item>
            <el-descriptions-item label="谷总电费(元)" label-class-name="my-label">
              <el-input size="small" v-model="formdata.valleyPrice" placeholder="自动计算" disabled></el-input>
            </el-descriptions-item>
          </el-descriptions>
          <el-descriptions :column="1" border direction="vertical" class="deitem-little">
            <el-descriptions-item label="总电费(元)" label-class-name="my-label">
              <el-input size="small" v-model="formdata.totalElectricityPrice" placeholder="自动计算" disabled></el-input>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-form>
    </div>
    <div class="table">
      <div class="title">
        <el-button type="primary" size="small" @click="adddevice" v-if="isonlylook">添加设备</el-button>
        <el-button type="primary" size="small" @click="submit" v-if="isonlylook">保 存</el-button>
        <div class="text"
          v-if="!isEmptyObj(danjia)"
        >尖:{{danjia.sharpElectricityUnitPrice}} 元/kWh 峰:{{danjia.peakElectricityUnitPrice}} 元/kWh 平:{{danjia.flatElectricityUnitPrice}} 元/kWh 谷:{{danjia.valleyElectricityUnitPrice}} 元/kWh</div>
      </div>
      <div class="tab">
        <TableColumn
          ref="tabledata"
          :tableData="tableData"
          :tableConfig="tableConfig"
        >
          <template #position>
            <el-table-column label="序号" width="70" type="index"></el-table-column>
            <el-table-column label="设备名称" width="200">
              <template #default="{ row,$index }">
                <el-select v-model="row.deviceId" placeholder="选择设备" size="small"  @change="handleDeviceChange" :disabled="!isonlylook">
                    <el-option v-for="item in deviceLists[$index] || []" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="开始时间" width="200">
              <template #default="{ row }">
                <el-date-picker 
                :disabled="!isonlylook"
                 v-model="row.fromDate"
                  size="small" 
                  value-format="yyyy-MM-dd HH:mm:ss" 
                  type="datetime" 
                  style="width:100%" 
                  placeholder="选择日期"
                  @change="generateTimePoints(row)">
          </el-date-picker>
              </template>
            </el-table-column>
            <el-table-column label="结束时间" width="200">
              <template #default="{ row }">
                <el-select v-model="row.toDate" filterable clearable placeholder="请选择结束时间" size="small">
                  <el-option
                    v-for="item in row.timePoints"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
          </template>
          <el-table-column label="操作" fixed="right" width="100" v-if="isonlylook">
            <template #default="{ row,$index }">
              <el-link type="primary" :underline="false" class="link"
              @click="postitem(row)"
                    >生成</el-link
                  >
                  <el-popconfirm
                    title="确定删除吗？"
                    @confirm="confirm(row,$index)"
                  >
                    <el-link slot="reference" type="danger" :underline="false">删除</el-link>
                  </el-popconfirm>
            </template>
          </el-table-column>
        </TableColumn>
      </div>
    </div>
  </div>
</template>
<script>
import { exportexcel } from '@/utils/excel'
import {getEquipListapi,getGenerateDataapi,getElectricityapi,postReportAddai,putReportAddai,postexportexcelapi,getBaseBuapi} from '@/api/ElectricalDistribution/energy-report'
import {getformdata} from './getform'
import TableColumn from '@/components/Table'
import dayjs from 'dayjs'
import { saveAs } from 'file-saver'
export default {
  name: 'CallPoliceAddReport',
  components: {
    TableColumn
  },
  props: {
    qiyelist: {
      type: Array,
      default: () => {
        ;[]
      }
    }
  },
  data() {
    return {
      value1: [],
      options: [],
      formdata: {reportName:'',createDate:''},
      tableData: [],
      tableConfig: [
        {
          label: '电量(kWh)',
          prop: 'thisValue',
          children: [
            { label: '尖电量', prop: 'sharpElectricity' },
            { label: '峰电量', prop: 'peakElectricity' },
            { label: '平电量', prop: 'flatElectricity' },
            { label: '谷电量', prop: 'valleyElectricity' },
            { label: '合计电量', prop: 'totalElectricity' }
          ]
        },
        {
          label: '总电费(元)',
          prop: 'thisValue',
          children: [
            { label: '尖电费', prop: 'sharpElectricityPrice' },
            { label: '峰电费', prop: 'peakElectricityPrice' },
            { label: '平电费', prop: 'flatElectricityPrice' },
            { label: '谷电费', prop: 'valleyElectricityPrice' },
            { label: '合计电费', prop: 'totalElectricityPrice' }
          ]
        }
      ],
      deviceLists:[],
      danjia:{},
      isupdate:false,
      isonlylook:true,
      rules:{
        reportName:[{ required: true, message: '请输入报表名称', trigger: 'blur' },],
        oilName:[{ required: true, message: '请输入油品名称', trigger: 'blur' },],
        createDate:[{ required: true, message: '请选择填报时间', trigger: 'change' },],
        oilTotal:[{ required: true, message: '请输入输油总量', trigger: 'blur' },],
        orgNo:[{ required: true, message: '请选择企业', trigger: 'change' },]
      }
    }
  },

  mounted() {
    this.gettime()
    this.$set(this.formdata,'orgNo',this.qiyelist[0]?.bizOrgNo)
  },

  methods: {
    // 保存
    async submit(){
      if(!this.tableData.length) return this.$message({type:'warning',message:'请先添加设备'})
      const total = this.formdata.totalElectricity;
      if(total === null || total === undefined || total === '')return this.$message({type:'warning',message:'请先至少生成一条数据'})
      await this.$refs.formrefs.validate()
       if(this.isupdate){
         var res=await putReportAddai({...this.danjia,...this.formdata,electricityDataList:this.tableData})
       }else{
         var res=await postReportAddai({...this.danjia,...this.formdata,electricityDataList:this.tableData})
       }
       this.$message({
        type:res.code=='200'?'success':'warning',
        message:res.code=='200'?`${this.isupdate?'修改':'新增'}成功`:res.message
       })
    },
    // 生成
    async postitem(row){
      if(!row.deviceId||!row.fromDate||!row.toDate)return this.$message({type:'warning',message:'请先选择设备 或开始/结束时间'})
      const res= await getGenerateDataapi({deviceId:row.deviceId,fromDate:row.fromDate,toDate:row.toDate,orgNo:this.formdata.orgNo})
      this.$message({
        type:res.code=='200'?'success':'warning',
        message:res.code=='200'?'生成成功':res.message
      })
      this.tableData = this.tableData.map(item => {
        if (item.deviceId === row.deviceId) {
          return {  ...res.data.entity }; // 合并原有属性和新数据
        }
        return item; // 保持其他元素不变
      });
      // 获取电价
      const toDate=this.tableData[this.tableData.length-1].toDate
      const {data:{entity}}=await getElectricityapi({orgNo:this.formdata.orgNo,toDate})
      this.danjia=entity
      // 计算列表中的累加值
      this.formdata={...this.formdata,...getformdata(this.tableData)}
    },
    generateTimePoints(row) {
      const array = [];
      // 转换为Date对象
      const startTime = new Date(row.fromDate);
      // 结束时间 = 开始时间 + 24小时
      const endTime = new Date(startTime.getTime() + 24 * 60 * 60 * 1000*30);
      // 当前处理的时间点，初始化为开始时间 + 15分钟
      let currentTime = new Date(startTime.getTime() + 15 * 60 * 1000);
      // 生成时间点数组
      while (currentTime <= endTime) {
        // 格式化时间点
        const formattedTime = this.formatDateTime(currentTime);
        // 添加到数组
        array.push({
          name: formattedTime,
          value: formattedTime
        });
        // 增加15分钟
        currentTime = new Date(currentTime.getTime() + 15 * 60 * 1000);
      }
      this.$set(row,'timePoints',array)
    },
    // 格式化日期时间为 yyyy-MM-dd HH:mm:ss
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    async toinfo(row,flag,look){
      this.isupdate=flag
      this.isonlylook=look
      const {data:{entity}}=await getBaseBuapi(row.id)
      const {sharpElectricityUnitPrice,peakElectricityUnitPrice,flatElectricityUnitPrice,valleyElectricityUnitPrice,electricityDataList,...obj}=entity
      this.danjia={sharpElectricityUnitPrice,peakElectricityUnitPrice,flatElectricityUnitPrice,valleyElectricityUnitPrice}
      this.formdata={...obj}
      this.tableData=electricityDataList
      this.tableData.forEach(ele=>this.generateTimePoints(ele))
      this.fetchAllDeviceLists();
    },
    // 设备下拉
    handleDeviceChange() {
      this.fetchAllDeviceLists();
    },
    // 获取设备列表
    async fetchAllDeviceLists() {
      // 遍历表格每一行，计算各自的设备列表
      for (let i = 0; i < this.tableData.length; i++) {
        // 收集除当前行外所有已选中的deviceId（非空）
        const alreadyExistsDeviceId = this.tableData
          .filter((row, index) => index!== i && row.deviceId) // 排除当前行，且deviceId非空
          .map(row => row.deviceId)
          .join(','); // 拼接成字符串参数
        // 调用接口获取当前行可用的设备列表
          const { data: { list } } = await getEquipListapi({
            orgNo: this.formdata.orgNo,
            alreadyExistsDeviceId // 传入过滤参数
          })
          this.$set(this.deviceLists, i, list);
      }
    },
    // 添加设备
    adddevice(){
      if(!this.formdata.orgNo) return this.$message({type:'warning',message:'请先选择企业'})
      this.tableData.push({deviceId:'',fromDate:'',toDate:''})
      this.fetchAllDeviceLists()
    },
    // 删除设备
    confirm(row,$index){
      this.tableData=this.tableData.filter((ele,index)=>index!==$index)
      this.fetchAllDeviceLists();
      this.formdata={...this.formdata,...getformdata(this.tableData)}
    },
    // 导出
    async exportlist(){
    const companyName=this.qiyelist.find(ele=>ele.bizOrgNo==this.formdata.orgNo)?.bizOrgName
      postexportexcelapi({companyName,...this.danjia,...this.formdata,electricityDataList:this.tableData}).then(res=>{
        const blobContent = new Blob([res])
        const url = window.URL.createObjectURL(blobContent)
        saveAs(url, `${this.formdata.reportName}.xls`)
      })
    },
    gettime() {
      this.$set(this.formdata, 'createDate', dayjs().format('YYYY-MM-DD HH:mm:ss'))
      this.$set(this.formdata, 'reportName', this.formdata.createDate+'能耗报表')
    },
    // 计算输油能耗
    getenergy(){
      if(!this.formdata.totalElectricity||!this.formdata.oilTotal) return
      const num=this.formdata.totalElectricity/this.formdata.oilTotal
      this.$set(this.formdata, 'oilEnergyConsumption',num.toFixed(3))
    },
    // 判断是否有电价
    isEmptyObj (obj){
      if (obj && typeof obj === 'object' && !Array.isArray(obj)) {
        return Object.keys(obj).length === 0;
      }
      return false; // 非对象类型直接返回 false
    },
    // 返回
    goback(){
      this.$refs.formrefs.resetFields()
      this.formdata={}
      this.danjia={}
      this.tableData=[]
      this.$emit('goback')
    }
  },
  watch:{
    'formdata.oilName'(newVal, oldVal){
      this.$set(this.formdata, 'reportName',newVal+ this.formdata.createDate+'能耗报表')
    },
    'formdata.oilTotal'(newval){
      this.getenergy()
    },
    'formdata.totalElectricityPrice'(newval){
      this.getenergy()
    }
  }
}
</script>
<style scoped lang="scss">
.addreport {
  height: 100%;
  padding: 20px;
  background-color: #fff;
  .table {
    margin-top: 20px;
    height: calc(100% - 295px);
    .title {
      display: flex;
      align-items: center;
      .text {
        color: #606266;
        font-size: 14px;
        margin-left: 20px;
      }
    }
    .tab {
      height: calc(100% - 110px);
      margin: 10px 0;
      .link{
        margin-right: 10px;
      }
      ::v-deep .el-input__inner{
        padding: 0 0 0 10px;
      }
      ::v-deep .el-input__prefix{
        display: none;
      }
    }
  }
  .back {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
  }
}
.descriptions{
  display: flex;
  .deitem-falst{
    width: 24%;
  }
  .deitem{
    width: 30%;
  }
  .deitem-little{
    width: 8%;
  }
}
::v-deep .my-label{
  background-color: #f5f5f5;
}
::v-deep .my-label-title{
  width: 13%;
}
::v-deep .el-descriptions__body{
  height: 100%;
}
::v-deep .el-descriptions__table{
  height: 100%;
}
::v-deep .el-form-item{
  margin-bottom: 0;
}
</style>
